import norAvatarImg from '@/assets/nor_avatar.jpg';
import { Dropdown, message } from 'antd';
import { MenuProps } from 'antd/lib';
import { history, RunTimeLayoutConfig } from 'umi';
import { ftUserinfo } from './service/modules/users';
import { clearLocalStorage } from './utils/local';

// 运行时配置代码完成
console.log('运行时配置代码完成');

// 全局路由监听
export function onRouteChange({ location, action }: any) {
  console.log('路由变化:', location.pathname, action);
  if (location.pathname !== '/login') {
    // 除了登录页，都要检测token
    if (!localStorage.getItem('token')) {
      history.replace('/login');
    }
  }
}

// 全局初始数据
export async function getInitialState() {
  let userInfo: any = {
    id: '',
    level: 0,
    telPhone: '',
    name: '游客',
    avatar: norAvatarImg,
  };
  if (!localStorage.getItem('token')) return userInfo;
  const res = await ftUserinfo();
  if (res.code === 200 && res.data) {
    const { id, level, telPhone, name, avatar } = res.data;
    return {
      id,
      level,
      telPhone,
      name,
      avatar,
    };
  }
}

// 配置全局layout

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const DropdownItems: MenuProps['items'] = [
    {
      key: 'logout',
      icon: '',
      label: '退出登录',
    },
    {
      key: 'theam',
      icon: '',
      label: '切换主题',
    },
  ];
  const DropdownOnClick: MenuProps['onClick'] = ({ key }) => {
    switch (key) {
      case 'logout':
        history.replace('/login');
        clearLocalStorage();
        break;
      case 'theam':
        message.warning('功能开发中....');
        break;
      default:
        break;
    }
  };

  return {
    logo: require('./assets/yay.jpg'), //左上角Logo
    title: '博客运营平台', //左上角Logo后面的名字
    menu: {
      locale: false, //菜单是否国际化
    },

    // 自定义 403 页面
    // unAccessible: <Page403 />,

    layout: 'mix', //菜单的方式，有mix,top,side三种，这里用mix
    splitMenus: false, // 这里用了mix才会生效,bia
    avatarProps: {
      src: initialState?.avatar || undefined, //右上角头像
      title: initialState?.name || '游客', //右上角名称
      size: 'small',
      render: (props, dom) => {
        return (
          <Dropdown
            menu={{
              items: DropdownItems,
              onClick: DropdownOnClick,
            }}
          >
            {dom}
          </Dropdown>
        );
      },
    },
  };
};
